import http from './request.js';

class LoginManager {
    constructor() {
        this.form = document.querySelector('form');
        this.emailInput = document.querySelector('input[type="email"]');
        this.passwordInput = document.querySelector('input[type="password"]');
        this.submitButton = document.querySelector('button[type="submit"]');
        this.errorMessage = document.querySelector('.error-message');
        
        this.init();
    }

    init() {
        this.bindEvents();
    }

    bindEvents() {
        this.form.addEventListener('submit', async (e) => {
            e.preventDefault();
            await this.handleSubmit();
        });

        // Real-time email format validation
        this.emailInput.addEventListener('input', () => {
            this.validateEmail();
        });
    }

    validateEmail() {
        const email = this.emailInput.value;
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            this.showError('Please enter a valid email address');
            return false;
        }
        this.hideError();
        return true;
    }

    showError(message) {
        this.errorMessage.textContent = message;
        this.errorMessage.style.display = 'block';
    }

    hideError() {
        this.errorMessage.style.display = 'none';
    }

    async handleSubmit() {
        if (!this.validateEmail()) {
            return;
        }

        const email = this.emailInput.value;
        const password = this.passwordInput.value;

        try {
            this.submitButton.disabled = true;
            const result = await http.post('/login', { email, password });
            
            // Save token
            http.setToken(result);
            
            // Login successful, redirect to homepage with current URL as redirect parameter
            window.location.href = `/index.html?redirect=${window.location.href}`;
        } catch (error) {
            this.showError(error.message || 'Login failed, please check your email and password');
        } finally {
            this.submitButton.disabled = false;
        }
    }
}

// Initialize login manager
new LoginManager(); 